#include "CaptureThread.h"
#include "MainWindow.h"
#include <QMutexLocker> 
#include <QDebug>


QImage MyQueue::pop()
{
    QMutexLocker lock(&m_mutex);
    if (isEmpty()) {
        return QImage();
    }
    return dequeue();
}


void MyQueue::push(QImage img)
{
    QMutexLocker lock(&m_mutex);
    if (size() > 2) {
        dequeue();
    }
    enqueue(img);
}





CaptureThread::CaptureThread(QObject* parent)
    : QThread(parent)
{
    m_flag = true;
    m_refresh = false;
    m_nImgIndex = 0;
    m_nStatIndex = 0;
}


void CaptureThread::SetParam(MainWindow* pWnd)
{
    m_pMainWnd = pWnd;
    m_queImage = pWnd->m_queImage;
}

void CaptureThread::SetPicturePath(QString strPath)
{
    m_strPictruePath = strPath;
    m_refresh = true;
}

void CaptureThread::stop()
{
    m_flag = false;
}

void CaptureThread::run()
{
    connect(this, &CaptureThread::fpsRate, m_pMainWnd, &MainWindow::on_fpsRate);

    QImage img(m_strPictruePath);
    // img = img.convertToFormat(QImage::Format_Grayscale8);
    // img = img.convertToFormat(QImage::Format_Indexed8);

    m_tmBeginTime = QTime::currentTime();
    while (m_flag) {
        if (m_refresh) {
            img = QImage(m_strPictruePath);
            m_refresh = false;
        }
        msleep(10);
        m_queImage->push(img);
        ++m_nImgIndex;
        if (m_tmBeginTime.msecsTo(QTime::currentTime()) >= 1000) {
            emit fpsRate(m_nImgIndex - m_nStatIndex);
            m_nStatIndex = m_nImgIndex;
            m_tmBeginTime = QTime::currentTime();
        }
    }
}

